<template>
  <el-tabs class="stock" v-model="activeName">
    <el-tab-pane label="已分配数据" name="first">
    </el-tab-pane>
    <el-tab-pane label="未分配数据" name="second">
    </el-tab-pane>
    <div class="select-group">
      <div class="items" v-show="activeName === 'first'">
        <span class="items-text">批次名称</span>
        <el-select v-model="getCurTempQuery().fileId" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in fileList"
            :key="item.fileId"
            :label="item.fileName"
            :value="item.fileId">
          </el-option>
        </el-select>
      </div>
      <div class="items" v-show="activeName === 'first'">
        <span class="items-text">所属公司</span>
        <el-select v-model="getCurTempQuery().companyId" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in companyArr"
            :key="item.companyId"
            :label="item.companyName"
            :value="item.companyId">
          </el-option>
        </el-select>
      </div>
      <div class="items" v-show="activeName !== 'first'">
        <span class="items-text">所属文件</span>
        <el-select v-model="getCurTempQuery().fileId" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in fileList"
            :key="item.fileId"
            :label="item.fileName"
            :value="item.fileId">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="select-group">
      <div class="items">
        <span class="items-text">行业</span>
        <el-select v-model="getCurTempQuery().industryId" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in industry"
            :key="item.industryId"
            :label="item.industryName"
            :value="item.industryId">
          </el-option>
        </el-select>
      </div>
      <div class="items" v-show="activeName !== 'first'">
        <span class="items-text">关键词</span>
        <el-select v-model="getCurTempQuery().keyword" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in keyword"
            :key="item.keywordId"
            :label="item.keywordName"
            :value="item.keywordName">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="select-group" >
      <div class="items" v-show="activeName === 'first'" style="width: 600px;display: inline-block;">
        <span class="items-text">导入时间 : </span>
        <el-date-picker
          v-model="tempQueryFirst.timeValue"
          type="datetimerange"
          value-format='yyyy-MM-dd HH:mm:ss'
          :picker-options="timeOption"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="left">
        </el-date-picker>
      </div>
      <el-button v-waves
                 :disabled="activeName === 'first' ? listLoading : inListLoading"
                 size="medium"
                 type="success"
                 class="el-icon-search"
                 @click="getList(activeName === 'first' ? STATUS_TEXT.alloted : STATUS_TEXT.unAllot)"
                 v-show="activeName === 'first'"
                 style="margin-left: 25px;"
      >
        <span style="padding-left:5px;">查询</span>
      </el-button>
    </div>
    <div class="select-group">
      <div class="items" v-show="activeName !== 'first'">
        <span class="items-text">系统标签</span>
        <el-select v-model="getCurTempQuery().sysLabel" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in systemlabel"
            :key="item.labelId"
            :label="item.labelName"
            :value="item.labelName">
          </el-option>
        </el-select>
      </div>
      <div class="items" v-show="activeName !== 'first'">
        <span class="items-text">号码归属地</span>
        <el-cascader
          filterable
          clearable
          change-on-select
          :options="areaList"
          v-model="getCurTempQuery().areaOptions">
        </el-cascader>
      </div>
      <el-button v-waves
                 :disabled="activeName === 'first' ? listLoading : inListLoading"
                 size="medium"
                 type="success"
                 class="el-icon-search"
                 @click="getList(activeName === 'first' ? STATUS_TEXT.alloted : STATUS_TEXT.unAllot)"
                 v-show="activeName !== 'first'"
      >
        <span style="padding-left:5px;">查询</span>
      </el-button>
    </div>
    <h4>
      数据列表
      <div style="display:inline-block" v-show="activeName!=='first'">
        <el-button v-waves
                   @click="batchEvent(false)" class="eventBtn"
                   type="primary"
                   size="small"
                   icon="el-icon-edit-outline">
          选中分配
        </el-button>
        <el-button v-waves
                   @click="batchEvent(true)" class="eventBtn"
                   type="primary"
                   size="small"
                   icon="el-icon-edit-outline">
          批量分配
        </el-button>
      </div>
    </h4>
    <el-table @selection-change="handleSelectionChange"
              empty-text="暂无任何用户信息"
              :data="activeName === 'first' ? list : inList "
              v-loading.body="activeName === 'first' ? listLoading : inListLoading"
              border
              fit
              style="width: 100%">
      <el-table-column
        v-if="activeName != 'first'"
        align="center"
        key="typeSelect"
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column v-if="activeName === 'first'" align="center" label="数据批次">
        <template slot-scope="scope">
          <router-link style="color:#409eff" :to="{path:'/allocation/detail',query:{id:scope.row.customerId}}">
            <span>{{scope.row.customerId}}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column v-if="activeName === 'first'" align="center" label="数量">
        <template slot-scope="scope">
          <span>{{ !!scope.row.companyName ? scope.row.companyName : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="所属公司">
        <template slot-scope="scope">
          <span>{{ !!scope.row.fileName ? scope.row.fileName : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="行业">
        <template slot-scope="scope">
          <span>{{scope.row.industryName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="分发人">
        <template slot-scope="scope">
          <span>{{ !!scope.row.keyword ? scope.row.keyword : '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审核进度">
        <template slot-scope="scope">
          <span>{{ !!scope.row.sysLabel ? scope.row.sysLabel : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审核人">
        <template slot-scope="scope">
          <span>{{ scope.row.provinceName + ( scope.row.cityName === '' ? '' :  '/' + scope.row.cityName ) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="分发时间">
        <template slot-scope="scope">
          <span>{{scope.row.virtualNumber}}</span>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="activeName === 'first' ? !listLoading : !inListLoading" class="pagination-container">
      <el-pagination background
                     @size-change="handleSizeChange"
                     prev-text="上一页"
                     next-text="下一页"
                     @current-change="handleCurrentChange"
                     :current-page="activeName === 'first' ? listQuery.current : inListQuery.current"
                     :page-sizes="[10,20,30,50]"
                     :page-size="activeName === 'first' ? listQuery.pagesize : inListQuery.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="activeName === 'first' ? total : inTotal">
      </el-pagination>
    </div>

    <el-dialog width="400px"
               :title="activeName === 'first' ? '移除' : '分配'"
               :visible.sync="infoFormVisible"
               @close="cancledialog('sendForm')"
    >
      <el-form :model="allot" :rules="rules" ref="sendForm">
        <!--这里必须套一个div 不然先点击批量后点击选中  弹框关闭时会报错-->
        <div>
          <el-form-item label="当前已选择 : "
                        v-show="!isBatch"
                        :label-width="formLabelWidth">
            <span>{{ multipleSelection.length }} 条</span>
          </el-form-item>
        </div>
        <div>
          <el-form-item prop="batchCount"
                        v-if="isBatch"
                        :label="activeName === 'first' ? '批量移除条数' : '批量分配条数'"
                        :label-width="formLabelWidth">
            <el-input style="width: 200px;" v-model.number.sync="allot.batchCount" type="number" placeholder="请输入条数"></el-input>
          </el-form-item>
        </div>
        <el-form-item v-if="activeName !== 'first'" label="所属公司" prop="allotSeleted" :label-width="formLabelWidth">
          <el-select v-model="allot.allotSeleted" clearable filterable placeholder="请选择">
            <el-option
              v-for="item in companyArr"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId">
            </el-option>
          </el-select>
        </el-form-item>
        <div>
          <el-form-item label="当前总条数 : "
                        :label-width="formLabelWidth">
            <span>{{ activeName === 'first' ? total : inTotal }} 条</span>
          </el-form-item>
        </div>
        <div v-if="activeName === 'second'" class="batchMark">
          {{ '注释:' + ( !isBatch ?
                                '使用于少量目标数据分配。将列表中勾选的数据分配给所选择的目标公司。'
                                :
                                '适用于大批量数据分配。输入想要分配的数据数量，选择目标公司。(一次最多分配'+ maxBatchNum +'条)')
          }}
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="() => isBatch ? batchSendEvent() : sendEvent()">{{ activeName === 'first' ? '移除' : '分配' }}</el-button>
        <el-button @click="infoFormVisible = false" size="mini">取 消</el-button>
      </div>
    </el-dialog>
  </el-tabs>
</template>
<script>
  import waves from '@/directive/waves' // 水波纹指令
  import {getIndustryList} from '@/api/user'  //获取行业信息
  import {
    getCompany,
    getKeyword,
    getSyslabel,
    getAreaList
  } from '@/api/dataStock'
  import {getFileList, getAllotList, setAllot ,batchAllot} from '@/api/allocation'

  export default {
    name: 'allocation',
    directives: {
      waves
    },
    data() {
      const timeOptions ={
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
      const getCurMaxNum = ()=>{
       return this.activeName === 'first' ? (this.total*1 > this.maxBatchNum ? this.maxBatchNum : this.total )
                                          : (this.inTotal*1 > this.maxBatchNum ? this.maxBatchNum : this.inTotal )
      }
      const CheckBatchNum = (rule, value, callback) => {
        let tempValue = value * 1;
        let maxNum = getCurMaxNum();
        if (!value) {
          callback(new Error('请输入要分配的条数'));
        } else if (!Number.isInteger(tempValue) || tempValue < 1) {
          this.allot.batchCount = '';
          callback(new Error('输入必须是大于0的数字'));
        } else if(tempValue > maxNum){
          this.allot.batchCount = '';
          callback(new Error(maxNum >= this.maxBatchNum ? '单次处理不能大于'+ maxNum +'条数' : '输入值不能大于'+ maxNum +'条数'));
        }else{
          callback();
        }
      }
      return {
        timeOption:timeOptions,
        maxBatchNum:2000,
        isBatch:true,
        STATUS_TEXT: {alloted: 1, unAllot: 2},
        areaList: [],
        companyArr: [],
        fileList: [],
        industry: [],
        keyword: [],
        systemlabel: [],
        allot: {
          allotSeleted: '', //所要分配的公司id
          batchCount:null
        },
        activeName: 'first',
        multipleSelection: [], //列选中的列id
        infoFormVisible: false,
        formLabelWidth: '120px',
        rules: {
          allotSeleted: [
            {required: true, message: '请选择要分配的公司', trigger: 'blur'},
          ],
          batchCount:[
            {validator: CheckBatchNum, trigger: 'blur'},
          ]
        },
        tempQueryFirst: { //已分配临时显示值
          timeValue:null,
          companyId: '',
          industryId: '',
          keyword: '',
          sysLabel: '',
          fileId: '',
          areaOptions: [],
        },
        tempQuerySecond: { //未分配临时显示值
          industryId: '',
          keyword: '',
          sysLabel: '',
          fileId: '',
          areaOptions: [],
        },
        searchQueryFirst:null, //已分配查询条件结果集
        searchQuerySecond:null,//未分配查询条件结果集
        listQuery: {
          current: 1,
          pagesize: 10,
        },
        list: [],
        total: null,
        listLoading: true,
        inListQuery: {
          current: 1,
          pagesize: 10
        },
        inList: [],
        inTotal: null,
        inListLoading: true,
      }
    },
    beforeRouteEnter(to,from,next){
      next(vm => {
        vm.$data.activeName = 'first';
          // 通过 `vm` 访问组件实例
        getCompany().then(res => {
          vm.$data.companyArr = res.data.info;
        }).catch(res => {
          vm.$message.error(res)
        })
        getFileList().then(res => {
          let temp = res.data.info;
          vm.$data.fileList = temp;
        }).catch(res => {
          vm.$message.error(res)
        })
      })
    },
    watch: {
      'activeName'(val) {
        this.multipleSelection = [];
      }
    },
    created() {
      this.getOptions(); //加载基础选项值
      this.getList(this.STATUS_TEXT.alloted); //请求已分配
      this.getList(this.STATUS_TEXT.unAllot); //请求未分配
    },
    methods: {
      getList(statusNum) {
        //保存查询当前查询条件
        statusNum === this.STATUS_TEXT.alloted ? this.searchQueryFirst = Object.assign({},this.getCurTempQuery(statusNum))
                                    : this.searchQuerySecond = Object.assign({},this.getCurTempQuery(statusNum));
        statusNum === this.STATUS_TEXT.alloted
                    ? this.listLoading = true
                    : this.inListLoading = true;
        let tempList = this.activeName === 'first' ? this.listQuery : this.inListQuery ;
        let tempObj = Object.assign({}, this.getCurTempQuery(statusNum), tempList, {status: statusNum});
        tempObj = this.transData(tempObj, statusNum);
        getAllotList(tempObj).then(response => {
          const temp = response.data;
          statusNum === this.STATUS_TEXT.alloted
            ? this.list = temp.info
            : this.inList = temp.info;
          statusNum === this.STATUS_TEXT.alloted
            ? this.total = temp.total
            : this.inTotal = temp.total;
          statusNum === this.STATUS_TEXT.alloted
            ? this.listLoading = false
            : this.inListLoading = false;
        }).catch(res => {
          statusNum === this.STATUS_TEXT.alloted
            ? this.listLoading = false
            : this.inListLoading = false;
          this.$message.error(res)
        })
      },
      getOptions() {
        getIndustryList().then(res => {
          let temp = res.data.info;
          this.industry = temp;
        }).catch(res => {
          this.$message.error(res)
        })
        getCompany().then(res => {
          this.companyArr = res.data.info;
        }).catch(res => {
          this.$message.error(res)
        })
        getKeyword().then(res => {
          let temp = res.data.info;
          this.keyword = temp;
        }).catch(res => {
          this.$message.error(res)
        })
        getSyslabel().then(res => {
          let temp = res.data.info;
          this.systemlabel = temp;
        }).catch(res => {
          this.$message.error(res)
        })
        getAreaList().then(res => {
          let temp = res.data.area;
          this.areaList = temp;
        }).catch(res => {
          this.$message.error(res)
        })
        getFileList().then(res => {
          let temp = res.data.info;
          this.fileList = temp;
        }).catch(res => {
          this.$message.error(res)
        })
      },
      handleSizeChange(val) {
        this.activeName === 'first' ? this.listQuery.pagesize = val
          : this.inListQuery.pagesize = val
        this.activeName === 'first' ? this.getList(this.STATUS_TEXT.alloted)
          : this.getList(this.STATUS_TEXT.unAllot)
      },
      handleCurrentChange(val){
        this.activeName === 'first' ? this.listQuery.current = val
                                    : this.inListQuery.current = val
        this.activeName === 'first' ? this.getList(this.STATUS_TEXT.alloted)
                                    : this.getList(this.STATUS_TEXT.unAllot)
      },
      sendEvent(){
        this.$refs.sendForm.validate(valid=>{
          if(!valid){
            return
          }
          if (!this.multipleSelection.length && !this.isBatch) { //如果未选中一条
            this.infoFormVisible = false;
            this.$message.error('您未有选中的操作项')
            return
          }
          let tempData = {customerId: this.multipleSelection};
          this.activeName === 'first' ? null : tempData['companyId'] = this.allot.allotSeleted;
          setAllot(tempData).then(res => {
            //完成后 再次请求两个列表
            this.getList(this.STATUS_TEXT.unAllot)
            this.getList(this.STATUS_TEXT.alloted)
            this.$message.success(this.activeName === 'first' ? '选中移除成功' : '选中分配成功');
            this.infoFormVisible = false;
          }).catch(res => {
            this.$message.error(res)
            this.infoFormVisible = false;
          })
        })
      },
      batchSendEvent(){ //批量操作
        this.$refs.sendForm.validate(valid=>{
          if(!valid){
            return
          }
          let fullLoading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
            //是否点击的批量
          let stus = this.activeName === 'first' ? 1 : 2 ;  // 1 : 批量删除  2 : 批量分配;
          let tempData = { count: this.allot.batchCount , status : stus};
          // 先获取 activeName 对应的 搜索结果集
          let tempQuery = this.activeName === 'first' ? this.searchQueryFirst : this.searchQuerySecond;
          this.activeName === 'first' ? null : tempData['companyId'] = this.allot.allotSeleted;
          tempData = this.transData(Object.assign({},tempQuery,tempData))
          batchAllot(tempData).then(res => {
            fullLoading.close(); //关闭遮罩
            //完成后 再次请求两个列表
            this.getList(this.STATUS_TEXT.unAllot)
            this.getList(this.STATUS_TEXT.alloted)
            this.$message.success(this.activeName === 'first' ? '批量移除成功' : '批量分配成功');
            this.infoFormVisible = false;
          }).catch(res => {
            fullLoading.close(); //关闭遮罩
            this.$message.error(res)
            this.infoFormVisible = false;
          })
        })
      },
      cancledialog(userForm) {
        //重置表单
        this.$refs[userForm].resetFields();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val.map(v => v.customerId);
      },
      transData(tempObj, status) {
        for (var k in tempObj) {
          if (k === 'areaOptions') {
            //提取地区的值
            if (tempObj[k].length) {
              tempObj['provinceId'] = tempObj[k][0];
              if (tempObj[k].length > 1) {
                tempObj['cityId'] = tempObj[k][1];
              }
              delete tempObj[k]
            } else {
              delete tempObj[k]
            }
          } else {
            //删除空值
            tempObj[k] === '' ? delete tempObj[k] : null;
          }
        }
        return tempObj
      },
      batchEvent(bool){
        this.infoFormVisible = true;
        this.isBatch = bool;
      },
      getCurTempQuery(statusNum){
        //有statusNum 就依据statusNum 来返回，没有就依据 activeName
        if(statusNum){
          return statusNum === this.STATUS_TEXT.alloted ? this.tempQueryFirst : this.tempQuerySecond
        }else{
          return this.activeName === 'first' ? this.tempQueryFirst : this.tempQuerySecond
        }
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .stock {
    .eventBtn {
      margin-left: 15px;
    }
    .dialog-Item {
      margin-bottom: 15px;
      margin-left: 15px;
      .textItem {
        display: inline-block;
        width: 40%;
      }
    }
    .info-item {
      margin: 15px 0px 15px 50px;
      > div {
        display: inline-block;
        min-width: 250px;
      }
      .tipText {
        display: inline-block;
        margin-right: 10px;
        min-width: 100px;
        text-align: right;
      }
    }
    .select-group {
      margin-left: 100px;
      margin-bottom: 15px;
      .items-text {
        display: inline-block;
        width: 95px;
        text-align: right;
        margin-right: 20px;
      }
      .items {
        width: 400px;
        display: inline-block;
      }
    }
    .batchMark {
      text-indent:35px;
      font-size: 12px;
      color:#888;
      margin: 0 15px;
    }
  }
</style>
